package com.bihua.iot.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.bihua.common.utils.StringUtils;
import com.bihua.iot.service.MqttService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author bihua
 * @date 2023年06月19日 10:25
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class MqttServiceImpl implements MqttService {

    @Value("${smqtt.smqttHttpUrl:http://127.0.0.1:60000/smqtt/}")
    private String smqttHttpUrl;

    @Override
    public String sendMessage(Map<String, Object> params) {
        log.info("MQTT Broker publish {}", params.toString());
        JSONObject param = new JSONObject();
        param.put("topic", params.get("topic"));
        param.put("qos", Integer.valueOf(params.get("qos").toString()));
        param.put("retain", Boolean.valueOf(params.get("retain").toString()));
        param.put("message", String.valueOf(params.get("message")));
        String result = HttpRequest.post(StringUtils.format("{}{}",smqttHttpUrl, "publish"))
            .header("Content-Type", "application/json;charset=UTF-8")
            .body(param.toString())
            .execute().body();
        return result;
    }

    @Override
    public String closeConnection(List<String> clientIdentifiers) {
        log.info("MQTT Broker 关闭连接 {}", clientIdentifiers.toString());
        JSONObject param = new JSONObject();
        param.put("ids", clientIdentifiers);
        String result = HttpRequest.post(StringUtils.format("{}{}",smqttHttpUrl, "close/connection"))
            .header("Content-Type", "application/json;charset=UTF-8")
            .body(param.toString())
            .execute().body();
        return result;
    }
}
